/* -*- mode: C; c-basic-offset: 8 -*-
 *
 * grep.c - A poor's man grep
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

char *
prettyline(char *line, char *word, int size_word)
{
	int max = 0;
	char *end_word = 0;
	char *res = 0;
	char *s, *t;

	max  = strlen(line) * 3;
	res = malloc(sizeof(char) * max + 1);
	assert(res != NULL);
	end_word = word + size_word;
	for (s=line, t=res; *s; s++, t++) {
		*t = *s;
		if (s >= word && s < end_word) {
			*++t = '\b';
			*++t = *s;
		}
	}
	*t = '\0';

	return res;
}

int
main(int argc, char *argv[])
{
	int res = 1;
	int size_pattern;
	char line[BUFSIZ];
	char *pattern = NULL;
	char *ptr = NULL;
	char *pline = NULL;
	char* (*stringstring)(const char *, const char *) = strstr;

	argv++;
	argc--;
	if (*argv && !strcmp(*argv, "-i")) {
		stringstring = strcasestr;
		argv++;
		argc--;
	}
	
	assert(*argv);
	pattern = *argv;
	size_pattern = strlen(pattern);

	while (fgets(line, BUFSIZ, stdin)) {
		if ((ptr = stringstring(line, pattern))) {
		  pline = prettyline(line, ptr, size_pattern);
			fputs(pline, stdout);
			res = 0;
			free(pline);
		}
	}

	return res;
}
